<template>
  <div class="table-container" v-loading="isLoading" element-loading-text="数据加载中...">
    <div class="header" v-if="isLoaded && baseInfo.currentProgressType">
      <div class="header__left">
        <div class="delay-risk">
          <div class="delay-risk__img">
            <img v-if="baseInfo.currentProgressType === 'delay_risk'" src="@/assets/images/image/construction-delay-title.png" />
            <img
              v-if="baseInfo.currentProgressType === 'no_time_out'"
              src="@/assets/images/image/construction-expect-title.png"
            />
            <img v-if="baseInfo.currentProgressType === 'time_out'" src="@/assets/images/image/construction-overdue-title.png" />
          </div>
          <div v-if="baseInfo.currentProgressType === 'delay_risk'">
            <div class="delay-risk__title">延期风险{{ baseInfo.delayRiskDay }}天</div>
            <div class="delay-risk__desc">
              实际已发生工期{{ baseInfo.currentFactWorkDay }}天+未来任务计划还需{{ baseInfo.futureWorkDay }}天-计划合同完工还需{{
                baseInfo.contractPlainWorkDay
              }}天
            </div>
          </div>
          <div v-if="baseInfo.currentProgressType === 'time_out'">
            <div class="delay-risk__title red-color">已超期{{ baseInfo.timeOutDay }}</div>
            <div class="delay-risk__desc">
              预计还需<span class="red-color">{{ baseInfo.estimateCompleted }}</span
              >天完工
            </div>
          </div>
          <div v-if="baseInfo.currentProgressType === 'no_time_out'">
            <div class="delay-risk__title black-color">预计还需{{ baseInfo.estimateCompleted }}天完工</div>
            <div class="delay-risk__desc">暂无延期风险</div>
          </div>
        </div>
        <div class="operate-list">
          <div class="operate-item" @click="showMakeDelayOrder = true">开客户延期单</div>
          <div class="operate-item">
            <div :class="['switch-list', startStopWorkIndex === 1 ? 'switch-list--active' : '']">
              <div
                class="switch-item"
                v-for="(item, index) in startStopWorkOptions"
                @click="changeStartStopWork(index)"
                :key="index"
                :class="['switch-item', startStopWorkIndex === index ? 'switch-item--active' : '']"
              >
                {{ item }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="header__right" v-if="baseInfo.delayRemind">
        <svg-icon iconClass="notice-icon" style="font-size: 16px" />
        <div class="notice">{{ baseInfo.delayRemind }}<span @click="showDelayOrderHistory = true">查看延期单</span></div>
      </div>
    </div>
    <div class="header header__bg" v-if="isLoaded && baseInfo.isDisplayStart">
      <el-button type="primary" @click="showWorkConfirm = true">开工确认</el-button>
    </div>
    <!--    start filter-select-->
    <div class="filter-select">
      <el-form :inline="true">
        <el-form-item label="任务名称">
          <select-remote
            v-model="searchForm.stageTaskId"
            @change-select="changeSelect($event, 'task')"
            @clear-select="clearSelect('task')"
            placeholder="请输入任务名称"
            :request-api="taskNameList"
            :params="{ customerId }"
            :defaultConfig="{ keyword: 'taskName', label: 'taskName', value: 'stageTaskId' }"
          ></select-remote>
        </el-form-item>
        <el-form-item label="负责人">
          <select-remote
            v-model="searchForm.userId"
            @change-select="changeSelect($event, 'director')"
            @clear-select="clearSelect('director')"
            placeholder="请输入负责人"
            :request-api="directorList"
            :params="{ customerId }"
            :defaultConfig="{ keyword: 'userName', label: 'userName', value: 'userId' }"
          ></select-remote>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-select
            v-model="searchForm.buildStatus"
            placeholder="请选择"
            clearable
            @clear="clearStatus"
            @change="getConstructionPlan"
          >
            <el-option v-for="item in taskStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="RefreshRight" plain @click="resetSearch">重置</el-button>
          <div class="construction-stage-btn" v-show="isStageSwitch">
            <el-switch size="large" v-model="isStartConstructionStage" :loading="isLoadingStart" @change="changeStartStage" />
            <span class="construction-stage-btn__label">施工阶段</span>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!--    end filter-select-->
    <!--    start filter-stage-->
    <div class="filter-stage">
      <div class="stage-list">
        <span class="stage-title">任务阶段：</span>
        <span
          class="stage-item"
          v-for="item in baseInfo.crmStageVOList"
          :key="item.stageId"
          @click="changeStage(item)"
          :class="{ 'stage-item--active': searchForm.stageId === item.stageId }"
          >{{ item.stageName }}</span
        >
      </div>
      <div class="filter-other">
        <span class="filter-other__notComplete">
          <svg-icon
            @click="changeIsCompletedTask"
            iconClass="radio-active"
            v-if="searchForm.isCompletedTask"
            style="font-size: 16px"
          />
          <svg-icon v-else @click="changeIsCompletedTask" iconClass="radio-default" style="font-size: 21px; margin-right: 3px" />
          不看已完成的任务</span
        >
        <span v-if="baseInfo.alterTaskLogNum > 0" class="filter-other__history" @click="showAdjustRecords = true"
          >查看历史调整记录（{{ baseInfo.alterTaskLogNum }}）</span
        >
      </div>
    </div>
    <!--    ende filter-stage-->
    <el-table
      ref="clientManagerRef"
      :data="tableData"
      stripe
      style="width: 100%"
      border
      :header-cell-style="{ background: '#F2F6FC', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
      :row-class-name="tableRowClassName"
    >
      <el-table-column prop="taskName" label="任务名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="userName" label="责任人" show-overflow-tooltip></el-table-column>
      <el-table-column label="计划工期" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.executeDays">{{ row.executeDays }}天</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="plainStartDate" label="计划开始" show-overflow-tooltip></el-table-column>
      <el-table-column prop="plainEndDate" label="计划完成" show-overflow-tooltip></el-table-column>

      <el-table-column prop="status" label="状态" show-overflow-tooltip>
        <template #default="{ row }">
          <span
            class="status-tag"
            :style="{ background: taskStatusObj[row.status].bgColor, color: taskStatusObj[row.status].color }"
            >{{ taskStatusObj[row.status].label }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="factStartDate" label="实际开始" show-overflow-tooltip></el-table-column>
      <el-table-column prop="factEndDate" label="实际完成" show-overflow-tooltip></el-table-column>
      <el-table-column prop="realDays" label="实际工期" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.realityDays">{{ row.realityDays }}天</span>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="延期天数" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.extensionDays > 0" style="color: #ff3333">{{ row.extensionDays }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column prop="isOut" label="是否外出" show-overflow-tooltip>
        <template #default="{ row }">
          <span>{{ row.isOut ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <div class="opt-buttons" v-show="[1, 2].includes(row.status)">
            <el-button type="primary" link size="small" @click="handleAdjustTime(row.stageTaskId)">调整计划</el-button>
          </div>
          <div class="opt-buttons" v-show="row.status === 2">
            <el-button type="primary" link size="small" @click="handelStage(row)">办理</el-button>
          </div>
          <div class="opt-buttons" v-show="row.status === 3">
            <el-button type="primary" link size="small" @click="handelCheckStage(row)">查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!--  TODO:和客户阶段办理页面/功能/组件一模一样,复制粘贴的目前没有封装   -->
    <!--  流程任务待办 start  -->
    <div class="client-stage-drawer">
      <el-drawer v-model="isShowProcessTask" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-intention">
          <title-view :title="taskInfo.taskName" />
          <div class="opt-instructions" ref="instructionsTitle">
            <el-icon>
              <QuestionFilled />
            </el-icon>
            <span @click="handelShowInstructions(proxy)">操作说明</span>
            <Transition name="fade">
              <div class="instructions-container" ref="instructionsContainer" v-show="instructionsVisible">
                <div class="arrow"></div>
                <title-view title="操作说明" isClose @close="handelCloseInstructions" />
                <div class="editor-container" v-html="taskInfo.remark"></div>
              </div>
            </Transition>
          </div>
          <div class="state-forms" v-loading="formRenderLoading" element-loading-text="数据加载中...">
            <template v-if="formItemsData.length">
              <FormRender ref="formRenderRef" :forms="formItemsData" :config="formConfigData" v-model="formModelData" />
            </template>
            <template v-else>
              <el-empty />
            </template>
          </div>
          <!--start next-task-->
          <div class="next-task-content" v-loading="isLoadingNextTask" element-loading-text="数据加载中...">
            <NextTaskList v-model="nextTaskList"></NextTaskList>
          </div>
          <!--end next-task-->
          <div class="state-btns">
            <el-button style="width: 92px; background-color: #f2f3f5" @click="handelCloseForm" size="default">取消 </el-button>
            <el-button
              style="width: 92px"
              v-if="!isDisableFollowUp && formItemsData.length"
              type="primary"
              @click="handelSubmitForm"
              :loading="isSubmitHandelLoading"
              :disabled="isUploadFile && !isGetUploadFileUrl"
              size="default"
              >确定
            </el-button>
          </div>
        </div>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <div class="tab-content">
            <CustomTabs v-model="currentCustomIndex" :tabList="referFollowTabs" @tab-change="changeTab" />
            <el-icon :size="20" @click="handelCloseForm">
              <Close />
            </el-icon>
          </div>
          <el-timeline
            v-if="currentCustomIndex === 0"
            style="max-width: 600px"
            :hollow="true"
            :class="{ 'hide-left-line': !followUpData.length }"
          >
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followTime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <div v-if="currentCustomIndex === 1" class="task-forms" v-loading="isLoadingReference">
            <template v-if="referenceForms.length">
              <div class="task-forms__item" v-for="item in referenceForms">
                <div class="form-title">{{ item.processModel?.formName }}</div>
                <div class="form-render">
                  <FormRender :forms="item.processModel.formItems" :config="{}" v-model="item.data" />
                </div>
              </div>
            </template>
            <el-empty v-else />
          </div>
        </div>
      </el-drawer>
    </div>
    <!--  流程任务待办 end  -->

    <!-- 跟进任务待办 start-->
    <div class="client-follow-drawer">
      <el-drawer v-model="isFollowDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <title-view title="跟进内容" isClose @close="handelCloseFollowDrawer" />
          <el-timeline style="max-width: 600px" :hollow="true" :class="{ 'hide-left-line': !followUpData.length }">
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followTime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
        </div>
      </el-drawer>
    </div>
    <!-- 跟进任务待办 end-->

    <!--  客户跟进 start  -->
    <follow-dialog v-if="isShowFollow" v-model="isShowFollow" :task-info="taskInfo" @submit-after="handleSubmitFollow" />
    <!--  客户跟进 end  -->

    <!--    start 历史调整记录-->
    <adjust-records-history v-model="showAdjustRecords" v-if="showAdjustRecords"></adjust-records-history>
    <!--    end 历史调整记录-->
    <!--    start 调整计划时间-->
    <adjust-plan-time
      v-if="showAdjustTime"
      v-model="showAdjustTime"
      :currentStageTaskId="currentStageTaskId"
      @adjustTimeSave="getConstructionPlan"
    ></adjust-plan-time>
    <!--    start 调整计划时间-->
    <!--    start 历史延期单-->
    <delay-records-history v-model="showDelayOrderHistory" v-if="showDelayOrderHistory"></delay-records-history>
    <!--    end 历史延期单-->
    <!--    start 停工-->
    <stop-work v-model="showStopWork" v-if="showStopWork" @stopWorkSave="refreshList"></stop-work>
    <!--    end 停工-->
    <!--    start 开客户延期单-->
    <make-delay-order v-model="showMakeDelayOrder" @makeDelayOrderSave="refreshList" v-if="showMakeDelayOrder"></make-delay-order>
    <!--    end 开客户延期单-->
    <!--    start 开工确认-->
    <work-confirm v-if="showWorkConfirm" v-model="showWorkConfirm" @workConfirmSave="refreshList"></work-confirm>
    <!--        end 开工确认-->
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick, toRefs } from "vue";
import { Clock, Close, Plus, QuestionFilled } from "@element-plus/icons-vue";
import { dayjs } from "element-plus";
import NextTaskList from "@/components/NextTaskList/index.vue";
import CustomTabs from "@/components/CustomTabs/index.vue";
import FollowDialog from "@/components/followDialog";
import { tableRowClassName } from "@/views/client/utils";
import { isHasFile, parseOrDefault } from "@/utils";
import {
  stageList,
  directorList,
  taskNameList,
  planList,
  operateWork,
  startStage,
  startStageAndReturn
} from "@/apis/constructionPlan";
import { clientInfoAndFollow, addTrack, subStageViewContent, roleList } from "@/apis/clientManager";
import { followTaskList } from "@/apis/myClient";
import defaultConfig from "@/settings";
import FormRender from "@/components/customComponents/formRender.vue";
import { pendingProcessModel, processInstanceForm, approvalForm, toDoNextTask } from "@/apis/workflow";
import { dictList } from "@/apis/dict/dict";
import useComputedParams from "@/hooks/useComputedParams";
import useIsUploadFile from "@/hooks/useIsUploadFile";
import useUserStore from "@/store/modules/user";
import { useElementPosition } from "../../hooks/instructionsPosition";
import { previewFormsList } from "@/apis/referenceData";
import { RefreshRight } from "@element-plus/icons-vue";
import AdjustRecordsHistory from "./components/AdjustRecordsHistory.vue";
import AdjustPlanTime from "@/components/AdjustPlanTime/index.vue";
import DelayRecordsHistory from "./components/DelayRecordsHistory.vue";
import StopWork from "./components/StopWork.vue";
import MakeDelayOrder from "./components/MakeDelayOrder.vue";
import WorkConfirm from "./components/WorkConfirm.vue";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const isLoading = ref(false);
const taskStatusObj = {
  1: { label: "未开始", bgColor: "#DCDFE6", color: "#606266" },
  2: { label: "进行中", bgColor: "#D9EDFF", color: "#409EFF" },
  3: { label: "已完成", bgColor: "#E3F9E9", color: "#14C85C" },
  4: { label: "已删除", bgColor: "#DCDFE6", color: "#606266" },
  6: { label: "审核中", bgColor: "#D9EDFF", color: "#409EFF" },
  null: { label: "状态错误", bgColor: "#DCDFE6", color: "#606266" }
};
const tableData = ref([]);
const getConstructionPlan = async () => {
  isLoading.value = true;
  const deepSearchParam = JSON.parse(JSON.stringify(searchForm.value));
  deepSearchParam.buildStatus = deepSearchParam.buildStatus === "" ? "all" : deepSearchParam.buildStatus;
  const { data } = await planList(props.customerId, deepSearchParam);
  tableData.value = data || [];
  isLoading.value = false;
};

/**
 * 流程任务待办
 */
const isShowProcessTask = ref(false);
const isSubmitHandelLoading = ref(false);
const handelSubmitForm = async () => {
  await nextTick();
  proxy.$refs.formRenderRef.submitForm(async data => {
    if (!data) {
      return proxy.$modal.msgError("请完善信息");
    }
    try {
      isSubmitHandelLoading.value = true;
      const postData = {
        deptId: userStore.userInfo.mainDeptId,
        formData: formModelData.value,
        processUsers: {},
        nextTicks: nextTaskList.value
      };
      await subStageViewContent(taskInfo.value.stageTaskId, postData);
      getConstructionPlan();
      proxy.$modal.msgSuccess("提交成功");
      isSubmitHandelLoading.value = false;
      isShowProcessTask.value = false;
    } catch (err) {
      isSubmitHandelLoading.value = false;
    }
  });
};
const handelCloseForm = async () => {
  await nextTick();
  if (formItemsData.value?.length) {
    await nextTick();
    proxy.$refs.formRenderRef.resetForm(() => {
      formItemsData.value = [];
      formModelData.value = {};
    });
  }
  currentCustomIndex.value = 0;
  followUpData.value = [];
  instructionsVisible.value = false;
  isShowProcessTask.value = false;
};
/**
 * 跟进任务待办
 */
const isFollowDrawer = ref(false);
const handleAddFollowUp = () => {
  isShowFollow.value = true;
};
const handelCloseFollowDrawer = () => {
  isFollowDrawer.value = false;
  followUpData.value = [];
};

/**
 * 办理/客户跟进弹窗
 */
const formRenderLoading = ref(false);
const isStateFollowLoading = ref(false);
const followUpData = ref([]);
const fllowUpTypes = ref([]);
const isDisableFollowUp = ref(false);
// 表单模型
const formConfigData = ref({});
const formItemsData = ref([]);
const formModelData = ref({});
// 是否有文件上传
// TODO: 没有考虑上传失败
const { isUploadFile, isGetUploadFileUrl } = toRefs(useIsUploadFile(formItemsData, formModelData));
const getProcessModel = async requestProcessModel => {
  try {
    formRenderLoading.value = true;
    const { formId: defId, formInstanceId, customerId } = taskInfo.value;
    const { data = {} } = await requestProcessModel(defId, customerId);
    formItemsData.value = parseOrDefault(data?.formItems, []);
    formConfigData.value = parseOrDefault(data?.formConfig, {});
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formInstanceId.value && getProcessInstanceForm();
    formRenderLoading.value = false;
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单实例模型
const getProcessInstanceForm = async () => {
  const { formInstanceId } = taskInfo.value;
  const { data } = await processInstanceForm(formInstanceId);
  formModelData.value = data || {};
  console.log(data, "<<<<<表单实例模型");
};
// 跟进类型
const followUpTypes = ref([]);
const getFllowUpType = async () => {
  const { data = [] } = await dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
  fllowUpTypes.value = data;
};
const getClientInfoAndFollow = customerId => {
  isStateFollowLoading.value = true;
  clientInfoAndFollow(customerId)
    .then(res => {
      const crmCustomerTrackList = res.data?.crmCustomerTrackList || [];
      followUpData.value = crmCustomerTrackList.map(item => {
        item.roleName = `${item.roleName}  ${item.updateBy}提交于${
          item?.updateTime ? dayjs(item.updateTime).format("HH:mm") : ""
        }`;
        const followItem = followUpTypes.value.filter(subItem => subItem.dictCode === item.trackType);
        followItem && (item.trackTypeName = followItem.dictLabel);
        return item;
      });
      isStateFollowLoading.value = false;
    })
    .catch(() => {
      isStateFollowLoading.value = false;
    });
};
const followDate = useComputedParams(time => {
  return dayjs(time).format("YYYY-MM-DD");
});
const followTime = useComputedParams(time => {
  return dayjs(time).format("hh:mm:ss");
});

// 办理/客户跟进弹窗
const taskInfo = ref({});
const handelStage = data => {
  isDisableFollowUp.value = false;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  isShowProcessTask.value = true;
  getProcessModel(pendingProcessModel);
  getNextTaskList(data);
  currentCustomIndex.value === 1 && getPreviewFormsList();
};
// 查看/客户跟进弹窗
const handelCheckStage = data => {
  isDisableFollowUp.value = true;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  isShowProcessTask.value = true;
  data.formInstanceId && getAuditAndToDoData();
};
// 表单模型——详情
const getAuditAndToDoData = async () => {
  try {
    formRenderLoading.value = true;
    const { data } = await approvalForm(taskInfo.value.formInstanceId);
    formRenderLoading.value = false;
    formItemsData.value = isHasFile(data?.formItems ?? [], data?.formData ?? {});
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formModelData.value = data?.formData || {};
  } catch (err) {
    formRenderLoading.value = false;
  }
};
/**
 * 操作说明
 */
const {
  instructionsVisible,
  instructionsLeft,
  instructionsTop,
  arrowLeft,
  arrowTop,
  handelShowInstructions,
  handelCloseInstructions
} = useElementPosition();

//跟进任务列表
const isShowFollow = ref(false);
const handleSubmitFollow = () => {
  const { customerId, currentType } = taskInfo.value;
  const isFollowTask = currentType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK;
  isFollowTask && (isShowFollow.value = false);
  getClientInfoAndFollow(customerId);
  proxy.$modal.msgSuccess("操作成功");
};

/**
 * 下个任务
 * */
const isLoadingNextTask = ref(false);
const nextTaskList = ref([]);
const getNextTaskList = async taskData => {
  try {
    isLoadingNextTask.value = true;
    const { data } = await toDoNextTask(taskData.stageTaskId);
    nextTaskList.value = data?.map(item => {
      return {
        ...item,
        plainStartDate: dayjs().format("YYYY-MM-DD")
      };
    });
    isLoadingNextTask.value = false;
  } catch (err) {
    isLoadingNextTask.value = false;
    console.log(err);
  }
};

/**
 * 任务参考
 */
const isLoadingReference = ref(false);
const referFollowTabs = ref([
  { label: "跟进记录", value: 0 },
  { label: "任务参考", value: 1 }
]);
const referenceForms = ref([]);
const getPreviewFormsList = async () => {
  try {
    isLoadingReference.value = true;
    const { data } = await previewFormsList(taskInfo.value.stageTaskId);
    referenceForms.value =
      data?.map(item => {
        const formItems = parseOrDefault(item.processModel?.formItems, []).map(item => {
          return {
            ...item,
            props: {
              ...item.props,
              disabled: true
            }
          };
        });
        return {
          processModel: {
            ...item.processModel,
            formItems
          },
          data: item.data ?? {}
        };
      }) || [];
    isLoadingReference.value = false;
  } catch (err) {
    isLoadingReference.value = false;
    console.log(err);
  }
};

/**
 * 切换跟进记录/任务参考
 */
const currentCustomIndex = ref(0);
const changeTab = index => {
  index === 0 && getClientInfoAndFollow(taskInfo.value.customerId);
  index === 1 && getPreviewFormsList();
};

//获取任务阶段+状态
const baseInfo = ref({});
const isLoaded = ref(false);
const getBaseInfo = async () => {
  const { data } = await stageList(props.customerId);
  baseInfo.value = data ?? {};
  if (Object.keys(data).length) {
    if (!searchForm.value.stageId && data?.crmStageVOList?.length) {
      searchForm.value.stageId = data?.crmStageVOList[0].stageId;
      searchForm.value.stageId && getConstructionPlan();
    }
    startStopWorkIndex.value = data?.buildEnable ? 1 : 0;
  }
  // 隐藏
  // baseInfo.value.currentProgressType = "no_time_out";
  isLoaded.value = true;
};

//开工停工
const showStopWork = ref(false);
const startStopWorkOptions = ref(["停工", "开工"]);
const startStopWorkIndex = ref(-1);
const changeStartStopWork = index => {
  if (startStopWorkIndex.value == index) return;
  if (index === 1) {
    proxy.$modal
      .confirm("请确认是否开工?")
      .then(async () => {
        let data = { customerId: props.customerId, type: 2 };
        await operateWork(data);
        proxy.$modal.msgSuccess("工地开工成功");
        await getBaseInfo();
      })
      .catch(() => {});
  } else {
    showStopWork.value = true;
  }
};

//搜索
const searchForm = ref({ stageId: "", stageTaskId: "", userId: "", buildStatus: "", isCompletedTask: false });
const taskStatusOptions = ref([
  { label: "未开始", value: "not_start" },
  { label: "进行中", value: "ing" },
  { label: "已完成", value: "complete" }
]);
const changeSelect = (data, type) => {
  if (type === "task") {
    searchForm.value.stageTaskId = data.stageTaskId;
  }
  if (type === "director") {
    searchForm.value.userId = data.userId;
  }
  getConstructionPlan();
};
const clearSelect = type => {
  if (type === "task") {
    searchForm.value.stageTaskId = "";
  }
  if (type === "director") {
    searchForm.value.userId = "";
  }
  getConstructionPlan();
};
const changeStage = item => {
  searchForm.value.stageId = item.stageId;
  getConstructionPlan();
};
const clearStatus = () => {
  searchForm.value.buildStatus = "";
  getConstructionPlan();
};
const changeIsCompletedTask = () => {
  searchForm.value.isCompletedTask = !searchForm.value.isCompletedTask;
  getConstructionPlan();
};
const resetSearch = () => {
  searchForm.value.taskName = "";
  searchForm.value.userId = "";
  searchForm.value.buildStatus = "";
  searchForm.value.stageTaskId = "";
  getConstructionPlan();
};

//历史调整记录
const showAdjustRecords = ref(false);

//历史延期单
const showDelayOrderHistory = ref(false);

//开客户延期单
const showMakeDelayOrder = ref(false);

//调整任务计划
const currentStageTaskId = ref("");
const showAdjustTime = ref(false);
const handleAdjustTime = stageTaskId => {
  currentStageTaskId.value = stageTaskId;
  showAdjustTime.value = true;
};

const refreshList = () => {
  getBaseInfo();
  getConstructionPlan();
};

//开工确认
const showWorkConfirm = ref(false);

/**
 * 是否可进入施工阶段
 */
const isStageSwitch = ref(false);
const getStageSwitch = async () => {
  try {
    isStateFollowLoading.value = true;
    const { data } = await clientInfoAndFollow(props.customerId);
    isStageSwitch.value = data?.isStageSwitch;
    isStartConstructionStage.value = data?.stage == 1 ? false : true;
    isStateFollowLoading.value = false;
  } catch (err) {
    isStateFollowLoading.value = false;
    console.log(err);
  }
};

/**
 * 进入施工阶段
 */
const isLoadingStart = ref(false);
const isStartConstructionStage = ref(false);
const changeStartStage = async () => {
  proxy.$modal
    .confirm(`确定${isStartConstructionStage.value ? "进入施工阶段" : "返回营销阶段"}吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })
    .then(async () => {
      try {
        isLoadingStart.value = true;
        await startStageAndReturn(props.customerId, isStartConstructionStage.value);
        getConstructionPlan();
        proxy.$modal.msgSuccess("操作成功");
        isLoadingStart.value = false;
      } catch (err) {
        isStartConstructionStage.value = !isStartConstructionStage.value;
        isLoadingStart.value = false;
      }
    })
    .catch(() => {
      isStartConstructionStage.value = !isStartConstructionStage.value;
    });
};

getStageSwitch();
getFllowUpType();
getBaseInfo();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
@use "constructionPlan";
// 操作说明
.instructions-container {
  @include mixin.flex-column;
  overflow: auto;
  position: fixed;
  left: v-bind(instructionsLeft);
  top: v-bind(instructionsTop);
  z-index: 9999;
  width: 400px;
  height: 90vh;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .arrow {
    position: fixed;
    left: v-bind(arrowLeft);
    top: v-bind(arrowTop);
    z-index: 9999;
    width: 0;
    height: 0;
    border: 14px solid transparent;
    border-left: 14px solid #fff;
  }
  .editor-container {
    flex: 1;
    width: 100%;
    overflow: auto;
  }
}
// 参考任务
.stage-follow-up {
  @include mixin.flex-column;
}
.task-forms {
  position: relative;
  flex: 1;
  overflow-y: auto;
  margin-top: 20px;
  :deep(.arco-empty) {
    @include mixin.position-center;
  }
  &__item {
    .form-title {
      margin-bottom: 5px;
      font-size: 14px;
      color: #3d3d3d;
      line-height: 22px;
    }
    .form-render {
      padding: 10px;
      background: #f6f8fa;
      border: 1px solid #dcdfe6;
    }
    & + .task-forms__item {
      margin-top: 20px;
    }
  }
  :deep(.el-empty) {
    @include mixin.position-center;
  }
  :deep(.form-item-el) {
    width: 100%;
  }
}
</style>
